package com.whfc.iot.mach.client;

import com.whfc.common.enums.DeviceType;
import com.whfc.common.enums.WorkState;
import com.whfc.common.util.DateUtil;
import com.whfc.common.util.JSONUtil;
import com.whfc.iot.mach.constant.MsgConst;
import com.whfc.iot.mach.entity.*;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class MachClientHandler extends ChannelInboundHandlerAdapter {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        logger.info("==============channel--register==============");
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        logger.info("==============channel--unregistered==============");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("==============channel--inactive==============");
    }

    // 连接成功后，向server发送消息
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("==============channel--active==============");

        for (int cnt = 0; cnt < 1; cnt++) {

            //发送0x03
            MachMsg0x03 msg0x03 = this.createMachMsg0x03();
            ctx.channel().writeAndFlush(msg0x03);
            logger.info("发送0x03:{}", JSONUtil.toPrettyString(msg0x03));

            // 发送0x01
            MachMsg0x01 machMsg0x01 = createMachMsg0x01();
            ctx.channel().writeAndFlush(machMsg0x01);
            logger.info("发送0x01:{}", JSONUtil.toPrettyString(machMsg0x01));
        }

    }

    // 接收server端的消息，并打印出来
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
        logger.info("==============channel--read==============");
        MachMsg machMsg = (MachMsg) obj;
        switch (machMsg.getCmd()) {
            case MsgConst.DOWNSTREAM_CMD_0x81:
                logger.info("接收0x81:{}", JSONUtil.toPrettyString(machMsg));
                TimeUnit.SECONDS.sleep(60);
                MachMsg0x01 machMsg0x01 = createMachMsg0x01();
                ctx.writeAndFlush(machMsg0x01);
                logger.info("发送0x01:{}", JSONUtil.toPrettyString(machMsg0x01));
                break;
            case MsgConst.DOWNSTREAM_CMD_0x82:
                MachMsg0x82 msg0x82 = (MachMsg0x82) machMsg;
                logger.info("接收0x82:{}", JSONUtil.toPrettyString(msg0x82));
                TimeUnit.SECONDS.sleep(15);
                MachMsg0x02 machMsg0x02 = createMachMsg0x02(msg0x82);
                ctx.writeAndFlush(machMsg0x02);
                logger.info("发送0x02:{}", JSONUtil.toPrettyString(machMsg0x02));
                break;
            case MsgConst.DOWNSTREAM_CMD_0x83:
                logger.info("接收0x83:{}", JSONUtil.toPrettyString(machMsg));
                TimeUnit.SECONDS.sleep(15);
                MachMsg0x01 machMsg0x01_1 = createMachMsg0x01();
                ctx.writeAndFlush(machMsg0x01_1);
                logger.info("发送0x01:{}", JSONUtil.toPrettyString(machMsg0x01_1));
                break;
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

    private MachMsg0x01 createMachMsg0x01() {
        Date now = new Date();
        List<MachWorkState> workStates = new ArrayList<>();
        workStates.add(new MachWorkState(DateUtil.addMinutes(now, -2), WorkState.RUN.getValue()));
        workStates.add(new MachWorkState(DateUtil.addMinutes(now, -1), WorkState.RUN.getValue()));
        workStates.add(new MachWorkState(DateUtil.addMinutes(now, -0), WorkState.RUN.getValue()));

        MachMsg0x01 msg = new MachMsg0x01();
        msg.setStartFlag(MsgConst.START_FLAG);
        msg.setDeviceType(DeviceType.mach.getValue());
        msg.setDeviceId(0x01);
        //msg.setLength(data0x01.getDataLength() + 11);
        msg.setSeq(0x01);
        msg.setCmd(MsgConst.UPSTREAM_CMD_0x01);

        msg.setWorkStates(workStates);
        msg.setBatteryState(0x01);
        msg.setBatteryPower(81);
        msg.setDeviceTemp(-23.6D);
        msg.setRotationX(30);
        msg.setRotationY(40);
        msg.setRotationZ(50);
        msg.setLngFlag("E");
        msg.setLatFlag("N");
        //114.433841,30.606224 武汉火车站
        //114.431567,30.453056 汇金中心
        msg.setLngWgs84(114.432841D);
        msg.setLatWgs84(30.605224D);
        msg.setOilPos(450);
        msg.setOilTemp(34.5D);
        msg.setOilState(0x01);
        msg.setOilPower(0x1F);
        msg.setMasterVer("1.0.0");
        msg.setSlaveVer("1.0.0");
        msg.setSpeed(68D);
        msg.setElevation(3500D);
        return msg;
    }

    private MachMsg0x02 createMachMsg0x02(MachMsg0x82 msg0x82) {
        MachMsg0x02 msg = new MachMsg0x02();

        msg.setStartFlag(MsgConst.START_FLAG);
        msg.setDeviceType(DeviceType.mach.getValue());
        msg.setDeviceId(0x01);
        //msg.setLength(data0x02.getDataLength() + 11)
        msg.setSeq(0x01);
        msg.setCmd(MsgConst.UPSTREAM_CMD_0x02);

        msg.setMasterOrSlave(1);
        msg.setVer("1.0.12");
        msg.setSubPackageTotal(msg0x82.getSubPackageTotal());
        msg.setSubPackageSeq(msg0x82.getSubPackageSeq());
        msg.setResult(1);
        return msg;
    }

    private MachMsg0x03 createMachMsg0x03() {
        MachMsg0x03 msg = new MachMsg0x03();

        msg.setStartFlag(MsgConst.START_FLAG);
        msg.setDeviceType(DeviceType.mach.getValue());
        msg.setDeviceId(0x01);
        //msg.setLength(data0x02.getDataLength() + 11)
        msg.setSeq(0x01);
        msg.setCmd(MsgConst.UPSTREAM_CMD_0x03);
        return msg;
    }

}
